import React, { useContext, useRef } from "react";
import update from "immutability-helper";
import { PlusCircleOutlined, DeleteOutlined } from "@ant-design/icons";
import { Button, Space } from "antd";
import { useHover } from "ahooks";
import DndFormCtx, { genButton } from "../core";
import classNames from "classnames";
import styles from "./index.module.less";

const BtnItem = ({
  title,
  onDelete,
  onSelect,
  isActived,
  isSystemBtn,
}: FunFormButton & {
  onDelete(): void;
  onSelect(): void;
  isActived: boolean;
}) => {
  const ref = useRef(null);

  const isHovering = useHover(ref);
  if (isSystemBtn)
    return (
      <Button type="primary" onClick={onSelect}>
        {title}
      </Button>
    );
  return (
    <div
      ref={ref}
      className={classNames(styles.btn, isActived && styles.actived)}
      onClick={onSelect}
    >
      <Button>{title}</Button>
      {isHovering && (
        <div
          className={styles.deleteIcon}
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
        >
          <DeleteOutlined />
        </div>
      )}
    </div>
  );
};

const Buttons = () => {
  const { instance, updateInstance, setActivedElement, activedElement } =
    useContext(DndFormCtx);

  return (
    <div className={styles.btns}>
      <Space>
        {instance.buttonGroups.map((btn, i) => {
          return (
            <BtnItem
              key={btn.title}
              isActived={activedElement?.element.uuid === btn.uuid}
              {...btn}
              onDelete={() => {
                updateInstance(
                  update(instance, {
                    buttonGroups: {
                      $splice: [[activedElement?.position.groupIndex || -1, 1]],
                    },
                  })
                );
              }}
              onSelect={() => {
                setActivedElement({
                  element: btn,
                  position: {
                    groupIndex: i,
                    rowIndex: 0,
                    cardIndex: 0,
                    colIndex: 0,
                  },
                });
              }}
            ></BtnItem>
          );
        })}
      </Space>
      <span
        className={styles.addBtn}
        onClick={() => {
          const newBtn = genButton({ title: "新增按钮" });
          updateInstance(
            update(instance, {
              buttonGroups: {
                $push: [newBtn],
              },
            })
          );
        }}
      >
        <PlusCircleOutlined style={{ marginRight: 12 }} />
        新增按钮
      </span>
    </div>
  );
};

export default Buttons;
